<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

/**
 * 课程回收站管理 
 */
class Subrecycle extends Backend
{
    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Subject.Subject');
        $this->Chaptermodel = model('Subject.Chapter');
    }
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with('category')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with('category')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = null)
    {
        $this->model->startTrans();
        $this->Chaptermodel->startTrans();
        $row = $this->model->onlyTrashed()->select($ids);
        if (empty($row)) {
            $this->error('当前课程不存在');
        }
        $chapers=$this->Chaptermodel->where(['subid'=>['IN',$ids]])->select();
        // 可以通过设置数据库表的外键设置成CASCADE
        $res=$this->Chaptermodel->where(['subid'=>['IN',$ids]])->delete();
        if(!$res){
            $this->error($this->Chaptermodel->getLastSql());  
        }
        $result = $this->model->destroy($ids,true);
        if (!$result) {
            $this->Chaptermodel->rollback();
            $this->error($this->model->getLastSql());
        }
        $this->model->commit();
        $this->Chaptermodel->commit();
        foreach($row as $item){
            is_file(ltrim($item['thumbs'], '/')) && unlink(ltrim($item['thumbs'], '/'));
           
        }
        foreach($chapers as $item){
            is_file(ltrim($item['url'], '/')) && unlink(ltrim($item['url'], '/'));
        }
        $this->success();
    }
    /*
    还原
    */ 
    public function restore($ids=null){
        $row = $this->model->onlyTrashed()->select($ids);
        if (empty($row)) {
            $this->error('当前课程不存在');
        }
        $res=$this->model->onlyTrashed()->where('id','IN',$ids)->update(['deletetime'=>null]);
         if($res==0){
                $this->error($this->model->getError());
        }
       $this->success();
    }
}
